<?php
namespace app\admin\controller;

use app\admin\lib\exception\BaseException;
use app\admin\service\LoginService;
use app\admin\service\AvatarService;
use app\admin\validate\Login as LoginValidate;
use app\BaseController;

class Login extends BaseController
{
    protected $loginService;
    protected $avatarService;

    protected function initialize()
    {
        parent::initialize();
        $this->loginService = new LoginService();
        $this->avatarService = new AvatarService();
    }

    public function login()
    {
        $data = $this->request->only(['username', 'password'], 'post');

        try {
            validate(LoginValidate::class)->scene('login')->check($data);
            $result = $this->loginService->login($data);

            return json([
                'code' => 200,
                'message' => '登录成功',
                'data' => $result
            ]);
        } catch (\Exception $e) {
            throw new BaseException([
                'code' => 400,
                'message' => $e->getMessage(),
                'errorCode' => 10000,
            ]);
        }
    }

    public function info()
    {
        $payload = $this->request->user;
        $result = $this->loginService->getUserInfo($payload['id']);

        return json([
            'code' => 200,
            'message' => '获取用户信息成功',
            'data' => $result
        ]);
    }

    /**
     * 用户修改
     */
    public function editSelf()
    {
        $currentUserId = $this->request->user['id'];
        $avatarFile = $this->request->file('avatar');
        $data = $this->request->only([
            'username', 'password', 'password_confirm', 'email', 'phone'
        ], 'post');

        try {
            // 处理头像上传
            if ($avatarFile) {
                $data['avatar'] = $this->avatarService->uploadAvatar($avatarFile, $currentUserId);
            }

            validate(LoginValidate::class)->scene('editSelf')->check($data);

            $result = $this->loginService->editSelf($currentUserId, $data);

            return json([
                'code' => 200,
                'message' => '个人信息编辑成功',
                'data' => $result
            ]);
        } catch (\Exception $e) {
            throw new BaseException([
                'code' => $e instanceof BaseException ? $e->getCode() : 400,
                'message' => $e->getMessage(),
                'errorCode' => $e instanceof BaseException ? $e->errorCode : 70009
            ]);
        }
    }

    // 修改logout方法中的token获取逻辑
    public function logout()
    {
        // 改回使用token请求头，与Auth中间件保持一致
        $authHeader = $this->request->header('token');
        if (empty($authHeader)) {
            throw new BaseException([
                'code' => 401,
                'message' => 'Token不存在，请先登录',
                'errorCode' => 10007
            ]);
        }
    
        // 兼容有Bearer前缀和没有前缀的情况
        if (preg_match('/^Bearer\s+(.+)$/i', $authHeader, $matches)) {
            $token = $matches[1];
        } else {
            $token = $authHeader;
        }
    
        $this->loginService->logout($token);
    
        return json([
            'code' => 200,
            'message' => '退出登录成功',
            'data' => null
        ]);
    }
}